package com.zoro.barn.business.service.sqldocument.business.document.controller;

import com.zoro.barn.business.service.sqldocument.conf.MongoDbConfig;
import com.zoro.barn.commons.mongodb.dao.MongoDao;
import com.zoro.barn.commons.webcommons.tools.WebContentUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

/**
 * @author zhaoxingwu
 */
@RestController
@RequestMapping("document-download")
public class FileDownloadController {

    private final MongoDao mongoDao;
    private final MongoDbConfig mongoDbConfig;

    public FileDownloadController(MongoDao mongoDao, MongoDbConfig mongoDbConfig) {
        this.mongoDao = mongoDao;
        this.mongoDbConfig = mongoDbConfig;
    }

    @RequestMapping("/image/{fileId}")
    public void image(@PathVariable("fileId") String fileId) throws Exception {
        if (StringUtils.isBlank(fileId)) {
            throw new NullPointerException("file id can not be null");
        }
        ByteArrayOutputStream os = this.mongoDao.download(mongoDbConfig.getDocumentImageDb(), fileId);
        HttpServletResponse response = WebContentUtil.getResponse();
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONNECTION, "close");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileId + ".jpg");
        try (OutputStream outputStream = response.getOutputStream()) {
            outputStream.write(os.toByteArray());
        }
    }
}
